package shajie.shajun.mmhf.View;

import android.Manifest;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;

import com.ToxicBakery.viewpager.transforms.AccordionTransformer;


import com.example.module_web.view.WebMainActivity;
import com.imnjh.imagepicker.SImagePicker;
import com.imnjh.imagepicker.activity.PhotoPickerActivity;

import org.zackratos.ultimatebar.UltimateBar;

import java.io.File;
import java.util.ArrayList;

import Util.UpdataUtil;
import shajie.shajun.mmhf.Base.BaseActivity;
import shajie.shajun.mmhf.Bean2.Result;
import shajie.shajun.mmhf.BuildConfig;
import shajie.shajun.mmhf.Control.CeHuaScrollView;
import shajie.shajun.mmhf.Control.NumAnim;
import shajie.shajun.mmhf.Control.fab.FloatingActionMenu;
import shajie.shajun.mmhf.Interface.CeHuaScrollInterface;
import shajie.shajun.mmhf.Public_Data;
import shajie.shajun.mmhf.R;
import shajie.shajun.mmhf.View.Dialog.UpdataDialog;
import shajie.shajun.mmhf.View.Fragment.Content1_Fragment;
import shajie.shajun.mmhf.View.Fragment.Content2_Fragment;
import shajie.shajun.mmhf.View.Fragment.GoodsPicture_Fragmnt;
import shajie.shajun.mmhf.View.Fragment.Picture_Fragmnt;
import shajie.shajun.mmhf.View.Fragment.Product_Detail_Fragment;
import shajie.shajun.mmhf.View.Fragment.Register_Fragment;
import shajie.shajun.mmhf.View.Fragment.SearchOrder_Fragment;
import shajie.shajun.mmhf.ViewModel.Bmobdata;
import shajie.shajun.mmhf.databinding.ActivityMainBinding;
public class MainActivity extends BaseActivity<ActivityMainBinding> implements View.OnClickListener{
    public ActivityMainBinding mainBinding;
    private ArrayList<Fragment> fragments=new ArrayList<>();
    private BottomNavigationView bottomNavigationView;
    private ViewPager mViewPager;
    private FrameLayout loginfraelayout;

    private ServiceConnection serviceConnection;
    private FragmentPagerAdapter mFragmentPagerAdapter;


    private String fileurl,filepath;

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    @Override
    public int setlayoutid() {
        return R.layout.activity_main;
    }
    @Override
    public void init(ActivityMainBinding binding) {
//        String path=Environment.getExternalStorageDirectory().getAbsolutePath() + "/11_APP/patch_signed_7zip.sjie";
//        TinkerInstaller.onReceiveUpgradePatch(getApplicationContext(), path);
//        //写入配置数据
//        SharedPreferences pref = getSharedPreferences("patch",
//                MODE_PRIVATE);
//        SharedPreferences.Editor editor = pref.edit();
//        editor.putInt("version", 300);
//        editor.commit();
//        //读取数据配置信息
//        int version = pref.getInt("version", 0);
//        boolean result = false;//pref.getBoolean("result", true);
//        if (version==300){
//            if (!result) {
//                Toast.makeText(this, "补丁成功", Toast.LENGTH_SHORT).show();
//                editor.putBoolean("result", true);
//                editor.commit();
//                if(new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/11_APP/patch_signed_7zip.sjie").exists()) {
//                    new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/11_APP/patch_signed_7zip.sjie").delete();
//                }else {
//                    toast("不存在2");
//                }
//            }
//
//        }
//        toast("022222");
//        Intent intent=new Intent(this,MyService.class);
//        startService(intent);
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        final Toolbar toolbar=(Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitleTextColor(Color.WHITE);
        toolbar.setTitle("团队力量需每个人能独挡一面");
        setSupportActionBar(toolbar);
        ActionBar actionBar=getSupportActionBar();
        if (actionBar!=null){
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_accounts);
            actionBar.setHomeButtonEnabled(true);
        }
        final UltimateBar ultimateBar=new UltimateBar(this);
        ultimateBar.setColorBar(getResources().getColor(R.color.blackgray),0);
        mainBinding=binding;

        //===========登录===================//
        binding.setOnclicklistener(this);
        //===========content===================//

        loginfraelayout=(FrameLayout)findViewById(R.id.loginframelayout) ;
        bottomNavigationView=(BottomNavigationView)findViewById(R.id.navigationView);
        mViewPager=(ViewPager)findViewById(R.id.noscrollviewpager);
        // Reference (or instantiate) a ViewPager instance and apply a transformer


//pager.setPageTransformer(true, new RotateUpTransformer());
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }
            @Override
            public void onPageSelected(int position) {
                    Public_Data.pagerselect=position;
                    mainBinding.fabLabel.setVisibility(position==0?View.VISIBLE:View.GONE);
                    bottomNavigationView.getMenu().getItem(position).setChecked(true);
            }
            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        binding.fabLabel.setOnMenuToggleListener(new FloatingActionMenu.OnMenuToggleListener() {
            @Override
            public void onMenuToggle(boolean opened) {
                if (opened){

                    mainBinding.fragmentContent1.setVisibility(View.VISIBLE);
                    mainBinding.fabSearchorder.setVisibility(View.VISIBLE);
                    mainBinding.fabDetail.setVisibility(View.VISIBLE);
                    mainBinding.fabPicture.setVisibility(View.VISIBLE);
                    mainBinding.fabGoodspicture.setVisibility(View.VISIBLE);
                    mainBinding.fabLabel.setAlpha(1.0f);
                    mainBinding.fabMmhf.setVisibility(View.VISIBLE);
                }else {

                    mainBinding.fragmentContent1.setVisibility(View.GONE);
                    mainBinding.fabSearchorder.setVisibility(View.GONE);
                    mainBinding.fabDetail.setVisibility(View.GONE);
                    mainBinding.fabPicture.setVisibility(View.GONE);
                    mainBinding.fabGoodspicture.setVisibility(View.GONE);
                    mainBinding.fabMmhf.setVisibility(View.GONE);
                    mainBinding.fabLabel.setAlpha(0.4f);
                }
            }
        });
        initbottomNavigationView();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main,menu);
        return super.onCreateOptionsMenu(menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){
            case android.R.id.home:
                break;
            case R.id.updatammhf:
                new UpdataDialog(this, filepath, new UpdataDialog.UpdataDialogCallBack() {
                    @Override
                    public void enter(final NotificationManager mNotificationManager,final Notification.Builder mBuilder,final ProgressDialog progressDialog){
                        UpdataUtil.getInstance(getApplicationContext(), new UpdataUtil.UpData_CallBack() {
                            @Override
                            public void start() {
                            }
                            @Override
                            public void complete(boolean b) {
                                //结束广播
                                if (b) {
                                    Toast.makeText(getApplicationContext(), "下载完成", Toast.LENGTH_SHORT).show();
                                    if (mNotificationManager!=null){
                                        mNotificationManager.cancel(1001);
                                    }
                                }
                            }
                            @Override
                            public void falie(String msg) {
                                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void progress(final long progress, long max) {
                                int len=(int)(((double) progress / (double) max) * 100.0f);
                                if (mBuilder!=null) {
                                    mBuilder.setProgress(100, len, false);
                                    String str = String.valueOf(len) + "%";
                                    mBuilder.setContentText(str);
                                    mNotificationManager.notify(1001, mBuilder.build());
                                }
                                if (progressDialog!=null) {
                                    progressDialog.setProgress(len);
                                }
                            }
                        }).moni();
                    }
                }).isprogressDialog(true)
                    .setImg(R.mipmap.ic_launcher)
                    .setVersion("V1.1.1")
                    .setUpdataContent("").show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.register:
                getSupportFragmentManager().beginTransaction()
                    .addToBackStack(null)
                    .setCustomAnimations(R.anim.in_from_left,R.anim.in_from_right,R.anim.out_from_left,R.anim.out_from_right)
                    .add(R.id.container,new Register_Fragment())
                    .commit();
                break;
            case R.id.fab_mmhf:
                mainBinding.fabLabel.close(true);
                Intent _intent=new Intent(MainActivity.this, WebMainActivity.class);
                startActivity(_intent);
                break;
            case R.id.fab_searchorder:
                mainBinding.fabLabel.close(true);
                getSupportFragmentManager().beginTransaction()
                        .addToBackStack(null)					        //添加返回键返回
                        .setCustomAnimations(R.anim.in_from_left,R.anim.in_from_right,R.anim.out_from_left,R.anim.out_from_right)
                        .replace(R.id.container,new SearchOrder_Fragment(),"SearchOrder_Fragment")
                        .commit();
                break;
            case R.id.fab_detail:
                mainBinding.fabLabel.close(true);
                getSupportFragmentManager().beginTransaction()
                        .addToBackStack(null)					        //添加返回键返回
                        .setCustomAnimations(R.anim.in_from_left,R.anim.in_from_right,R.anim.out_from_left,R.anim.out_from_right)
                        .replace(R.id.container,new Product_Detail_Fragment(),"Product_Detail_Fragment")
                        .commit();
                break;
            case R.id.fab_picture:
                mainBinding.fabLabel.close(true);
                getSupportFragmentManager().beginTransaction()
                        .addToBackStack(null)					        //添加返回键返回
                        .setCustomAnimations(R.anim.in_from_left,R.anim.in_from_right,R.anim.out_from_left,R.anim.out_from_right)
                        .replace(R.id.container,new Picture_Fragmnt(),"Picture_Fragmnt")
                        .commit();
                break;
            case R.id.fab_goodspicture:
                mainBinding.fabLabel.close(true);
                SImagePicker
                        .from(this)
                        .maxCount(9)
                        .rowCount(3)
                        .showCamera(true)
                        .pickMode(SImagePicker.MODE_IMAGE)
                        .forResult(101);
                break;
        }
    }
    Content2_Fragment mContent2_fragment;
    public void initbottomNavigationView() {
        fragments.clear();
        mContent2_fragment=new Content2_Fragment();
        fragments.add(new Content1_Fragment());
       // fragments.add(new PieChart_30_Fragment());
        fragments.add(mContent2_fragment);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int tab=0;
                switch (item.getItemId()) {
                    case R.id.test1:
                        tab=0;
                        //mainBinding.fabLabel.setVisibility(View.VISIBLE);
                        item.setChecked(true);
                        break;
                    case R.id.test2:
                        tab=1;
                       // mainBinding.fabLabel.setVisibility(View.GONE);
                        item.setChecked(true);
                        break;
                }
                mViewPager.setCurrentItem(tab);
                return false;
            }

        });
        mViewPager.setOffscreenPageLimit(2);
        mFragmentPagerAdapter=new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        };
        mViewPager.setAdapter(mFragmentPagerAdapter);
        mViewPager.setPageTransformer(true, new AccordionTransformer());
        onResume();
    }
    public void refresh(){
        mContent2_fragment.sectionsPagerAdapter.mOutGoods_fragment.refreshFruits();
    }
    private void unbindService() {
        if(null != serviceConnection) {
            unbindService(serviceConnection);
            serviceConnection = null;
        }
    }
    @Override
    protected void onDestroy() {
        unbindService();
        if (Public_Data.files!=null){
            for (int i = 0; i < Public_Data.files.size(); i++) {
                if(new File(Public_Data.files.get(i)).exists()) new File(Public_Data.files.get(i)).delete();

            }
        }
        super.onDestroy();
    }
    @Override
    protected void onPause() {
        unbindService();
        super.onPause();
    }
    @Override
    protected void onResume() {
        super.onResume();

    }
    @Override
    protected void onRestart() {
        super.onRestart();
    }
    @Override
    protected void onStop() {
        unbindService();
       // getFloatService().show();
        super.onStop();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10) {
            if (Build.VERSION.SDK_INT >= 23) {
                if (!Settings.canDrawOverlays(this)) {
                    // SYSTEM_ALERT_WINDOW permission not granted...
                    Toast.makeText(this,"not granted",Toast.LENGTH_SHORT);
                }else {
                    Toast.makeText(this, "success", Toast.LENGTH_SHORT).show();
                }
            }
            return;
        }
        if (resultCode == Activity.RESULT_OK ) {
            final ArrayList<String> pathList =
                    data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT_SELECTION);
            final boolean original =
                    data.getBooleanExtra(PhotoPickerActivity.EXTRA_RESULT_ORIGINAL, false);
            Bmobdata.uppictures(this.getApplicationContext(), pathList, new Bmobdata.Singer<Result>() {
                @Override
                public void success(Result s) {
                    Toast.makeText(MainActivity.this, s.getResult(), Toast.LENGTH_SHORT).show();
                }
                @Override
                public void faile(String s) {
                    Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
                }
            });

        }
    }
}
